//
//  YLYMainViewController.m
//  iAccounts
//
//  Created by 楊盧银Mac on 14-4-25.
//  Copyright (c) 2014年 com.yly16. All rights reserved.
//

#define Seconds_of_Minute 60
#define Minutes_of_Hour 60
#define Hours_of_Day 24
#import "NVCalendar.h"
#import "TWSpringyFlowLayout.h"
#import "YLYMainViewController.h"
#import "PostViewController.h"

NSString * const kTWMessageViewControllerCellIdentifier = @"Cell";

// Numerics
CGFloat const kTWMessageViewControllerCellPadding = 10;
CGFloat const kTWMessageViewControllerCellHeight = 90;
@interface YLYMainViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
@property (strong , nonatomic)UITableView *latelyZBTableView;  //最近笔记
@end

@implementation YLYMainViewController

-(id)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self) {
        
    }
    return self;
}

-(void)viewDidLoad{
    //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    
    self.navigationController.navigationBar.tintColor = [UIColor greenColor];
    
    if([[DatabaseManager shareManager] getSettings].length == 0){
        _currentNote = [[DatabaseManager shareManager]showCurrentlyByNoteName:@"默认账本"];
        [[DatabaseManager shareManager] setSettings];
    }else{
        _currentNote = [[DatabaseManager shareManager]showCurrentlyByNoteName:[[DatabaseManager shareManager] getSettings]];
    }
    self.title = _currentNote.noteName;
    
    [self.collectionView setCollectionViewLayout:[[TWSpringyFlowLayout alloc]init]];
    self.collectionView.backgroundColor = [UIColor clearColor];
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"green.jpg"] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
    dtForMonth = [NSDate date];
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:dtForMonth];
    NSInteger month = [components month];
    YearNumber = [components year];
    MonthNumber = month;
    //YearNumber = 0;

    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];//实例化一个NSDateFormatter对象
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];           //设定时间格式,这里可以设置成自己需要的格式
    
    NSDate *Startdate =[dateFormat dateFromString:[NSString stringWithFormat:@"%d-0%d-01 00:00:00",YearNumber,month]];
    NSString *endDateStr = [self getBeginAndEndWithDate:Startdate];
    int endDay = [[[endDateStr componentsSeparatedByString:@"."] lastObject] integerValue];
    NSDate *Enddate = [dateFormat dateFromString:[NSString stringWithFormat:@"%d-%d-%d 00:00:00",YearNumber,month,endDay]];
    //NSDate *Enddate =[dateFormat dateFromString:[NSString stringWithFormat:@"%d-0%d-30 00:00:00",year,month]];
    NSMutableArray *list = [[DatabaseManager shareManager]showBillByDate:Startdate toDate:Enddate toType:nil];
    
    
    
    
}

-(void)viewWillAppear:(BOOL)animated{
    //显示全部笔记>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    [self.BillLabel setText:[NSString stringWithFormat:@"全部帐单：%@",@([[DatabaseManager shareManager]numberOfBills])]];
    self.billList = [[DatabaseManager shareManager] ShowUpToDateBillWithNumber:3];
    [self.latelyZBTableView reloadData];
}
- (void)loadView
{
    
	[super loadView];
	
	//self.navigationItem.title = @"Messages";
	
	// Background
	UIImageView *backgroundImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"messages_bg_2.png"]];
	backgroundImageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    backgroundImageView.alpha = 0.6;
	[self.view insertSubview:backgroundImageView belowSubview:self.collectionView];
	
	// Parallax effect
	UIInterpolatingMotionEffect *interpolationHorizontal = [[UIInterpolatingMotionEffect alloc]initWithKeyPath:@"center.x" type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis];
    interpolationHorizontal.minimumRelativeValue = @-20.0;
    interpolationHorizontal.maximumRelativeValue = @20.0;
	
    UIInterpolatingMotionEffect *interpolationVertical = [[UIInterpolatingMotionEffect alloc]initWithKeyPath:@"center.y" type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis];
    interpolationVertical.minimumRelativeValue = @-20.0;
    interpolationVertical.maximumRelativeValue = @20.0;
	
    [backgroundImageView addMotionEffect:interpolationHorizontal];
    [backgroundImageView addMotionEffect:interpolationVertical];
    
	// Configurte collection view
    
    //    [self.collectionView registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:kTWMessageViewControllerCellIdentifier];
    //    self.collectionView.delegate = self;
    //    self.collectionView.dataSource = self;
}

#pragma mark - UICollectionView DataSource & Delegate methods

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 6;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kTWMessageViewControllerCellIdentifier forIndexPath:indexPath];
    
    
    if (indexPath.row == 0) {
        /*
        UILabel *JiYiBiLable = [[UILabel alloc]initWithFrame:CGRectMake(20, 0, 60, 45)];
        [JiYiBiLable setTextColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"green.jpg"]]];
        [JiYiBiLable setText:@"记一笔"];
        [cell addSubview:JiYiBiLable];
         */
        NSArray *imagelist = @[@"brush_32x32",@"camera_32x32",@"image_32x32",@"plus_32x32"];
        for (int i = 0; i < 4; i++) {
            
            UIButton *imageViewbt = [UIButton buttonWithType:UIButtonTypeCustom];
            [imageViewbt setImage:[UIImage imageNamed:imagelist[i]] forState:UIControlStateNormal];
            [imageViewbt setFrame:CGRectMake(16+70*i, 2.5, 55, 55)];
            [imageViewbt.layer setCornerRadius:imageViewbt.frame.size.height / 2];
            [imageViewbt.layer setBorderColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"green.jpg"]].CGColor];
            [imageViewbt setTag:i];
            [imageViewbt addTarget:self action:@selector(TopImageBuuton:) forControlEvents:UIControlEventTouchUpInside];
            [imageViewbt.layer setBorderWidth:1.5];
            [imageViewbt.layer setMasksToBounds:YES];
            [cell addSubview:imageViewbt];
        }
        cell.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.8];
        cell.layer.cornerRadius = 10;
        cell.layer.borderWidth = 1;
        cell.layer.borderColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"green.jpg"]].CGColor;
    }
    
    if (indexPath.row == 1) {
        UIImageView *imagView = [[UIImageView alloc]initWithFrame:CGRectMake(5, 10, 20, 20)];
        [imagView setImage:[UIImage imageNamed:@"article_32x32"]];
        [cell addSubview:imagView];
        UILabel *ZDLable = [[UILabel alloc]initWithFrame:CGRectMake(28, 10, 100, 20)];
        [ZDLable setTextColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"green.jpg"]]];
        [ZDLable setText:@"最近帐单 "];
        [cell addSubview:ZDLable];
        
        self.BillLabel = [[UILabel alloc]initWithFrame:CGRectMake(152, 0, 120, 20)];
        [self.BillLabel setTextColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"green.jpg"]]];
        //显示全部笔记>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        /*
        [self.BillLabel setText:[NSString stringWithFormat:@"全部帐单：%@",@([[DatabaseManager shareManager]numberOfBills])]];
        [cell addSubview:self.BillLabel];
        
        UIButton *gotoAllZDBt = [UIButton buttonWithType:UIButtonTypeCustom];
        [gotoAllZDBt setImage:[UIImage imageNamed:@"arrow_right_alt1_32x32"] forState:UIControlStateNormal];
        gotoAllZDBt.tag = 4;
        [gotoAllZDBt addTarget:self action:@selector(TopImageBuuton:) forControlEvents:UIControlEventTouchUpInside];
        gotoAllZDBt.frame = CGRectMake(270, 0, 20, 20);
        [cell addSubview:gotoAllZDBt];
         */
    }
    if (indexPath.row == 2) {
        self.latelyZBTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 44*3)];
        self.latelyZBTableView.delegate = self;
        self.latelyZBTableView.dataSource = self;
        self.latelyZBTableView.backgroundColor = [UIColor clearColor];
        [cell addSubview:self.latelyZBTableView];
        cell.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.8];
        cell.layer.cornerRadius = 10;
        cell.layer.borderWidth = 1;
        cell.layer.borderColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"green.jpg"]].CGColor;
        
        UIButton *btt = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        btt.frame = CGRectMake(0, 44*3, 320, 45);
        [btt setTitle:@"更多账单..." forState:UIControlStateNormal];
        [btt setTag:4];
        [btt addTarget:self action:@selector(TopImageBuuton:) forControlEvents:UIControlEventTouchUpInside];
        btt.tintColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"green.jpg"]];
        [cell addSubview:btt];
    }
    if (indexPath.row == 3) {
    
        
        int width = cell.bounds.size.width/4;
        NSArray *imageName = @[@"book_alt_32x32",@"chart_32x32",@"equalizer_32x32",@"compass_32x32"];
        NSArray *Name = @[@"账本",@"图表",@"预算",@"位置"];
        for (int i = 0; i < 4; i++) {
            UIImageView *imagView = [[UIImageView alloc]initWithFrame:CGRectMake(width*i, 6, 30, 30)];
            //[imagView setImage:[self reSizeImage:[UIImage imageNamed:[imageName objectAtIndex:i]] toSize:CGSizeMake(25, 25)]];
            imagView.image = [UIImage imageNamed:[imageName objectAtIndex:i]];
            imagView.layer.cornerRadius = imagView.bounds.size.height/2;
            imagView.layer.borderWidth = 1;
            imagView.layer.borderColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"green.jpg"]].CGColor;
            imagView.layer.masksToBounds = YES;
            [cell addSubview:imagView];
            
            UILabel *ZDLable = [[UILabel alloc]initWithFrame:CGRectMake(35+width*i, 0, 100, 45)];
            [ZDLable setTextColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"green.jpg"]]];
            [ZDLable setText:[Name objectAtIndex:i]];
            [cell addSubview:ZDLable];
            
            UIButton *gotoAllZBBt = [UIButton buttonWithType:UIButtonTypeCustom];
            gotoAllZBBt.tag = 5+i;
            [gotoAllZBBt addTarget:self action:@selector(TopImageBuuton:) forControlEvents:UIControlEventTouchUpInside];
            gotoAllZBBt.frame = CGRectMake(5+width*i, 6, 30, 30);
            [cell addSubview:gotoAllZBBt];
        }
        
        cell.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.8];
        cell.layer.cornerRadius = 10;
        cell.layer.borderWidth = 1;
        cell.layer.borderColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"green.jpg"]].CGColor;
    }
    /*
    if (indexPath.row == 4) {
        UIImageView *imagView = [[UIImageView alloc]initWithFrame:CGRectMake(5, 6, 30, 30)];
        [imagView setImage:[UIImage imageNamed:@"chart_32x32"]];
        [cell addSubview:imagView];
        UILabel *ZDLable = [[UILabel alloc]initWithFrame:CGRectMake(35, 0, 100, 45)];
        [ZDLable setTextColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"green.jpg"]]];
        [ZDLable setText:@"我的图表 "];
        [cell addSubview:ZDLable];
        
        UILabel *ZDNumLable = [[UILabel alloc]initWithFrame:CGRectMake(152, 0, 120, 45)];
        [ZDNumLable setTextColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"green.jpg"]]];
        
        UIImageView *iamagV = [[UIImageView alloc]init];
        iamagV.frame = CGRectMake(265, 6, 30, 30);
        iamagV.image = [UIImage imageNamed:@"arrow_right_alt1_32x32"];
        [cell addSubview:iamagV];
        
        
        UIButton *gotoAllZBBt = [UIButton buttonWithType:UIButtonTypeCustom];
        gotoAllZBBt.tag = 6;
        [gotoAllZBBt addTarget:self action:@selector(TopImageBuuton:) forControlEvents:UIControlEventTouchUpInside];
        gotoAllZBBt.frame = cell.bounds;
        [cell addSubview:gotoAllZBBt];
        
        
        cell.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.8];
        cell.layer.cornerRadius = 10;
        cell.layer.borderWidth = 1;
        cell.layer.borderColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"green.jpg"]].CGColor;
    }
    if (indexPath.row == 5) {
        UIImageView *imagView = [[UIImageView alloc]initWithFrame:CGRectMake(5, 6, 30, 30)];
        [imagView setImage:[UIImage imageNamed:@"equalizer_32x32"]];
        [cell addSubview:imagView];
        UILabel *ZDLable = [[UILabel alloc]initWithFrame:CGRectMake(35, 0, 100, 45)];
        [ZDLable setTextColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"green.jpg"]]];
        [ZDLable setText:@"账单预算 "];
        [cell addSubview:ZDLable];
        
        UILabel *ZDNumLable = [[UILabel alloc]initWithFrame:CGRectMake(152, 0, 120, 45)];
        [ZDNumLable setTextColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"green.jpg"]]];
        
        UIImageView *iamagV = [[UIImageView alloc]init];
        iamagV.frame = CGRectMake(265, 6, 30, 30);
        iamagV.image = [UIImage imageNamed:@"arrow_right_alt1_32x32"];
        [cell addSubview:iamagV];
        
        
        UIButton *gotoAllYSBt = [UIButton buttonWithType:UIButtonTypeCustom];
        gotoAllYSBt.tag = 7;
        [gotoAllYSBt addTarget:self action:@selector(TopImageBuuton:) forControlEvents:UIControlEventTouchUpInside];
        gotoAllYSBt.frame = cell.bounds;
        [cell addSubview:gotoAllYSBt];
        
        
        cell.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.8];
        cell.layer.cornerRadius = 10;
        cell.layer.borderWidth = 1;
        cell.layer.borderColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"green.jpg"]].CGColor;
    }
    if (indexPath.row == 6) {
        UIImageView *imagView = [[UIImageView alloc]initWithFrame:CGRectMake(5, 6, 30, 30)];
        [imagView setImage:[UIImage imageNamed:@"compass_32x32"]];
        [cell addSubview:imagView];
        UILabel *ZDLable = [[UILabel alloc]initWithFrame:CGRectMake(35, 0, 100, 45)];
        [ZDLable setTextColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"green.jpg"]]];
        [ZDLable setText:@"账单位置 "];
        [cell addSubview:ZDLable];
        
        UILabel *ZDNumLable = [[UILabel alloc]initWithFrame:CGRectMake(152, 0, 120, 45)];
        [ZDNumLable setTextColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"green.jpg"]]];
        
        UIImageView *iamagV = [[UIImageView alloc]init];
        iamagV.frame = CGRectMake(265, 6, 30, 30);
        iamagV.image = [UIImage imageNamed:@"arrow_right_alt1_32x32"];
        [cell addSubview:iamagV];
        
        
        UIButton *gotoAllYSBt = [UIButton buttonWithType:UIButtonTypeCustom];
        gotoAllYSBt.tag = 8;
        [gotoAllYSBt addTarget:self action:@selector(TopImageBuuton:) forControlEvents:UIControlEventTouchUpInside];
        gotoAllYSBt.frame = cell.bounds;
        [cell addSubview:gotoAllYSBt];
        
        
        cell.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.8];
        cell.layer.cornerRadius = 10;
        cell.layer.borderWidth = 1;
        cell.layer.borderColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"green.jpg"]].CGColor;
    }
     
    if (indexPath.row == 4) {
        UIImageView *imagView = [[UIImageView alloc]initWithFrame:CGRectMake(5, 0, 30, 30)];
        [imagView setImage:[UIImage imageNamed:@"clock_32x32"]];
        [cell addSubview:imagView];
        UILabel *ZDLable = [[UILabel alloc]initWithFrame:CGRectMake(28, 0, 250, 30)];
        [ZDLable setTextColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"green.jpg"]]];
        [ZDLable setText:@"  日历时间       \t\t\t\t标记"];
        [cell addSubview:ZDLable];
        
        
        UIImageView *imageView2 = [[UIImageView alloc]init];
        imageView2.frame = CGRectMake(270, 0, 30, 30);
        imageView2.image = [UIImage imageNamed:@"tag_stroke_32x32"];
        [cell addSubview:imageView2];
    }
     */
    if (indexPath.row == 4) {
        self.nvClendar = [[NVCalendar alloc]initWithFrame:cell.bounds];
        self.nvClendar.delegate = self;
        self.nvClendar.tag = 20;
        UIView *bkgrdView=[[UIView alloc]initWithFrame:cell.bounds];
        bkgrdView.backgroundColor=[UIColor whiteColor];
        [cell addSubview:bkgrdView];
        [bkgrdView addSubview:self.nvClendar];
        
        [self showCalendar:MonthNumber];
//        cell.backgroundColor = [UIColor colorWi thWhite:1.0 alpha:0.8];
        cell.layer.cornerRadius = 10;
        cell.layer.borderWidth = 1;
        cell.layer.borderColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"green.jpg"]].CGColor;
        cell.backgroundColor = [UIColor whiteColor];
        caIndexPath = indexPath;

    }
    if (indexPath.row == 5) {
        cell .backgroundColor = [UIColor clearColor];
    }
    
	return cell;
}

//=======
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return CGSizeMake(self.view.bounds.size.width - (kTWMessageViewControllerCellPadding*2), 60);
    }
    if (indexPath.row == 1) {
        return CGSizeMake(self.view.bounds.size.width - (kTWMessageViewControllerCellPadding*2), 30);
    }
    if (indexPath.row == 2) {
        return CGSizeMake(self.view.bounds.size.width - (kTWMessageViewControllerCellPadding*2), 44*4);
    }
    if (indexPath.row == 3) {
        return CGSizeMake(self.view.bounds.size.width - (kTWMessageViewControllerCellPadding*2), 45);
    }
    /*
    if (indexPath.row == 4) {
        return CGSizeMake(self.view.bounds.size.width - (kTWMessageViewControllerCellPadding*2), 45);
    }
    
    if (indexPath.row == 5) {
        return CGSizeMake(self.view.bounds.size.width - (kTWMessageViewControllerCellPadding*2), 45);
    }
    if (indexPath.row == 6) {
        return CGSizeMake(self.view.bounds.size.width - (kTWMessageViewControllerCellPadding*2), 45);
    }
     
    if (indexPath.row == 4) {
        return CGSizeMake(self.view.bounds.size.width - (kTWMessageViewControllerCellPadding*2), 30);
    }
     */
    if (indexPath.row == 4) {
         return CGSizeMake(self.view.bounds.size.width - (kTWMessageViewControllerCellPadding*2), 150);
    }
    return CGSizeMake(self.view.bounds.size.width - (kTWMessageViewControllerCellPadding*2), 30);
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 2;
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 8;
}
#pragma mark Button
-(void)TopImageBuuton:(UIButton*)sender{
    NSLog(@"%@",sender);
    if (sender.tag == 0) {
    
        [self performSegueWithIdentifier:@"CreateBill" sender:self];
    }
    if (sender.tag == 1) {
        [self openCamera];
    }
    if (sender.tag == 2) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
            UIImagePickerController *pickerView = [[UIImagePickerController alloc]init];
            
            pickerView.sourceType =  UIImagePickerControllerSourceTypePhotoLibrary;
            pickerView.delegate = self;
            pickerView.allowsEditing= YES;
            [self presentViewController:pickerView animated:YES completion:nil];
        }
    }
    if (sender.tag == 4) {
        [self performSegueWithIdentifier:@"first2BillTable" sender:self];
    }
    if (sender.tag == 5) {
        [self performSegueWithIdentifier:@"firstToNote" sender:self];
    }
    if (sender.tag == 6) {
        [self performSegueWithIdentifier:@"firstToPie" sender:self];
    }
    if (sender.tag == 7) {
        [self performSegueWithIdentifier:@"2yusuan" sender:self];
    }
    if (sender.tag == 8) {
        [self performSegueWithIdentifier:@"main2map" sender:self];
    }
}
-(void)showCalendar:(int)number{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:dtForMonth];
    NSInteger month = number;
    NSInteger year = YearNumber;
    NSInteger day = [components day];;
//    if (MonthNumber > 12) {
//        MonthNumber = 1;
//        month = [components month]+MonthNumber;
//        year = [components year]+1;
//        day = [components day];
//    }
//    if (MonthNumber < 0){
//        month = [components month]+MonthNumber;
//        year = [components year]-1;
//        day = [components day];
//    }
//    if (MonthNumber >= 0 && MonthNumber < 12) {
//        month = MonthNumber;
//        year = [components year];
//        day = [components day];
//    }
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSRange totaldaysForMonth = [gregorian rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:dtForMonth];//total days of particular month
    dtForMonth = [dtForMonth dateByAddingTimeInterval:Seconds_of_Minute*Minutes_of_Hour*Hours_of_Day*totaldaysForMonth.length];
    
    NSDateFormatter *dt = [[NSDateFormatter alloc] init];
    NSString *strMonthName = [[dt monthSymbols] objectAtIndex:month-1];//January,Febryary,March etc...
    strMonthName = [ strMonthName stringByAppendingString:[NSString  stringWithFormat:@"- %d",year]];
//    self.nvClendar.layer.masksToBounds = YES;
//    self.nvClendar.layer.shadowColor = [UIColor blackColor].CGColor;
//    //_navView.layer.shadowOffset = CGSizeMake(10, 10);
//    self.nvClendar.layer.shadowOpacity = 0.4;
//    self.nvClendar.backgroundColor = [UIColor whiteColor];
//    self.nvClendar.layer.cornerRadius = 5.0;
//    self.nvClendar.layer.borderColor = [UIColor blackColor].CGColor;
//    self.nvClendar.layer.borderWidth = 2.0;
   
    self.nvClendar = [self.nvClendar createCalOfDay:day Month:month Year:year MonthName:strMonthName];
}
-(void)changeMonth:(BOOL)isup{
    UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:caIndexPath];
    self.nvClendar = (NVCalendar*)[cell viewWithTag:20];
    
    CATransition *animation = [CATransition animation];
    animation.delegate = self;
    animation.duration = 2;
    animation.timingFunction = UIViewAnimationCurveEaseInOut;
	animation.fillMode = kCAFillModeForwards;
	animation.endProgress = 2;
	animation.removedOnCompletion = NO;
    if (isup) {
        MonthNumber ++;
        if (MonthNumber > 12) {
            MonthNumber = 1;
            YearNumber ++;
        }
        animation.type = @"pageCurl";//101
    }
    else{
        MonthNumber--;
        if (MonthNumber < 1) {
            MonthNumber = 12;
            YearNumber --;
        }
        animation.type = @"pageUnCurl";//102
    }
    
    [self.nvClendar.superview.layer addAnimation:animation forKey:@"animation"];
	self.lastAnimation = animation;
    
    UIView *bkgrdView=self.nvClendar.superview;
    [self.nvClendar removeFromSuperview];
    self.nvClendar = [[NVCalendar alloc]initWithFrame:cell.bounds];
    self.nvClendar.delegate = self;
    self.nvClendar.tag = 20;
        [self showCalendar:MonthNumber];
    [bkgrdView addSubview:self.nvClendar];
    


//    [self showCalendar:MonthNumber];
}
- (IBAction)firstToSettingView:(id)sender {
    [self performSegueWithIdentifier:@"first2Setting" sender:self];
}
#pragma mark tableView Delegata

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.billList.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *TableSampleIdentifier = @"TableSampleIdentifier";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
                             TableSampleIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]
                initWithStyle:UITableViewCellStyleDefault
                reuseIdentifier:TableSampleIdentifier];
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 2, 40, 40)];
        [cell addSubview:imageView];
        imageView.tag=100;
        
        UILabel *moneyLabel = [[UILabel alloc]initWithFrame:CGRectMake(60, 0, 100, 44)];
        moneyLabel.tag = 101;
        
        [moneyLabel setTextColor:[UIColor redColor]];
        [cell addSubview:moneyLabel];
        
        UILabel *timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(235, 11, 100, 22)];
        timeLabel.tag = 102;
        timeLabel.font = [UIFont fontWithName:@"Helvetica" size:12];
        [cell addSubview:timeLabel];
        
//        UILabel *payoutLabel = [[UILabel alloc]initWithFrame:CGRectMake(235, 0, 100, 22)];
//        payoutLabel.tag = 103;
//        payoutLabel.textColor = [UIColor grayColor];
//        payoutLabel.font = [UIFont fontWithName:@"Helvetica" size:12];
//        [cell addSubview:payoutLabel];
        
        UILabel *typeLabel = [[UILabel alloc]initWithFrame:CGRectMake(150, 0, 100, 44)];
        typeLabel.tag = 104;
        typeLabel.textColor = [UIColor orangeColor];
        typeLabel.font = [UIFont fontWithName:@"Helvetica" size:15];
        [cell addSubview:typeLabel];
    }
    
    cell.backgroundColor = [UIColor clearColor];
//    if (indexPath.row == self.billList.count) {
//        cell.textLabel.text = [NSString stringWithFormat:@"账单流水..."];
//        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//        return cell;
//    }
//    if (self.billList.count == 0) {
//        return cell;
//    }
    iBill *aBill = [self.billList objectAtIndex:indexPath.row];
    iBillTypeSub *sub = [[DatabaseManager shareManager]showBillSubTypeByTypeID:aBill.billTypeSubID.intValue];
    UIImageView *imageView = (UIImageView*)[cell viewWithTag:100];
    imageView.image = [UIImage imageWithData:sub.typeSubImageData];

    
    
    UILabel *moneyLabel = (UILabel *)[cell viewWithTag:101];
    if (aBill.isPayOut.boolValue == NO) {
        moneyLabel.textColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"green.jpg"]];
    }
    else{
        moneyLabel.textColor = [UIColor redColor];
    }
    moneyLabel.text = [NSString stringWithFormat:@"￥%.2f",aBill.billMoney.floatValue];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    
    
    //zzz表示时区，zzz可以删除，这样返回的日期字符将不包含时区信息。
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    NSString *destDateString = [dateFormatter stringFromDate:aBill.billTime];
    UILabel *timeLabel = (UILabel *)[cell viewWithTag:102];
    timeLabel.text = destDateString;
    
//    UILabel *payLabel = (UILabel *)[cell viewWithTag:103];
//    payLabel.text = [NSString stringWithFormat:@"<%@>",aBill.isPayOut.boolValue?@"收入":@"支出"];
    
    UILabel *typeLabel = (UILabel *)[cell viewWithTag:104];
    
    typeLabel.text = sub.typeSubName;
    
    
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == self.billList.count) {
        [self performSegueWithIdentifier:@"first2BillTable" sender:self];
        return;
    }
    self.aBill = [self.billList objectAtIndex:indexPath.row];
    [self performSegueWithIdentifier:@"CreateBill" sender:self];
}
//TODO:???????>>>>>>>>>>>>>>
- (IBAction)SynchronousDataToNet:(UIButton *)sender {
    CABasicAnimation *basicAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    basicAnimation.delegate = self;
    basicAnimation.fromValue = @(-M_PI);
    basicAnimation.timeOffset = 5.0f;
    basicAnimation.repeatCount = 5;
    basicAnimation.autoreverses = NO;
    
    [sender.layer addAnimation:basicAnimation forKey:@"animation"];
    //[self login];
}

- (IBAction)SearchBill:(UIButton *)sender {
}
- (void)configureNotification:(BOOL)toAdd {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kNotificationTakePicture object:nil];
    if (toAdd) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(callbackNotificationForFilter:) name:kNotificationTakePicture object:nil];
    }
}
- (void)callbackNotificationForFilter:(NSNotification*)noti {
    UIViewController *cameraCon = noti.object;
    if (!cameraCon) {
        return;
    }
    UIImage *finalImage = [noti.userInfo objectForKey:kImage];
    if (!finalImage) {
        return;
    }
    PostViewController *con = [[PostViewController alloc] init];
    con.postImage = finalImage;
    
    if (cameraCon.navigationController) {
        [cameraCon.navigationController pushViewController:con animated:YES];
    } else {
        [cameraCon presentModalViewController:con animated:YES];
    }
}

- (void)openCamera {
    SCNavigationController *nav = [[SCNavigationController alloc] init];
    nav.scNaigationDelegate = self;
    [nav showCameraWithParentController:self];
}

#pragma mark - SCNavigationController delegate
-(NSIndexPath*)indexsPathFromView:(UIView*)view
{
    UIView *parentView = [view superview];
    
    while (![parentView isKindOfClass:[UITableViewCell class]] && parentView!=nil) {
        parentView = parentView.superview;
    }
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:(UICollectionViewCell*)parentView];
    NSLog(@"%d",indexPath.row);
    return indexPath;
}
- (void)didTakePicture:(SCNavigationController *)navigationController image:(UIImage *)image {
//    PostViewController *con = [[PostViewController alloc] init];
//    con.postImage = image;
//    [navigationController pushViewController:con animated:YES];
    self.photoData = UIImageJPEGRepresentation(image, 1.0f);
    
    [self dismissViewControllerAnimated:YES completion:nil];
    [self performSegueWithIdentifier:@"CreateBill" sender:self];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *image = info[UIImagePickerControllerEditedImage];
    self.photoData = UIImageJPEGRepresentation(image, 1.0f);
    
    [self dismissViewControllerAnimated:YES completion:nil];
    [self performSegueWithIdentifier:@"CreateBill" sender:self];
}
//TODO:传值
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    NSObject *NewVC = [segue destinationViewController];
    if ([segue.identifier isEqualToString:@"CreateBill"]) {
        if (self.photoData != nil) {
            [NewVC setValue:self.photoData forKey:@"photoData"];
        }
        if (self.aBill != nil) {
            [NewVC setValue:self.aBill forKey:@"aBill"];
            self.aBill = nil;
        }
    }
    if ([segue.identifier isEqualToString:@"2DayBill"]){
        [NewVC setValue:self.daybillList forKey:@"billList"];
    }
}
//TODO:
- (void)login
{
    
    time_t currentTime;
    time(&currentTime);
    
    if ((currentTime - loginTime) > 2)
    {
        NSArray *permissions = [NSArray arrayWithObjects:@"all", nil];
        [[[sdkCall getinstance] oauth] authorize:permissions inSafari:NO];
        
        loginTime = currentTime;
    }
}
//TODO:📅日历的delegate
-(void)topbillAtDay:(NSArray *)billList{
    self.daybillList = billList;
    if (billList.count == 0) {
        UIAlertView *alc = [[UIAlertView alloc]initWithTitle:@"提示" message:@"亲！这一天没有记账哟，是否记账呢？" delegate:self cancelButtonTitle:@"记一笔" otherButtonTitles:@"算了，下次吧", nil];
        [alc show];
    }
    else if(billList.count == 1){
        self.aBill = [billList objectAtIndex:0];
        [self performSegueWithIdentifier:@"CreateBill" sender:self];
    }
    else{
        
        [self performSegueWithIdentifier:@"2DayBill" sender:self];
    }
}

//TODO:根据一个date得到这个date的一个月的开始日期到结束日期
- (NSString *)getBeginAndEndWithDate:(NSDate *)date{
    NSDate *newDate = date;
    double interval = 0;
    NSDate *beginDate = nil;
    NSDate *endDate = nil;
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    [calendar setFirstWeekday:2];//设定周一为周首日
    BOOL ok;
    ok = [calendar rangeOfUnit:NSMonthCalendarUnit startDate:&beginDate interval:&interval forDate:newDate];
    //分别修改为 NSDayCalendarUnit NSWeekCalendarUnit NSYearCalendarUnit 可查年、月、周开始结束 “某个时间点”所在的“单元”的起始时间，以及起始时间距离“某个时间点”的时差（单位秒）
    if (ok) {
        endDate = [beginDate dateByAddingTimeInterval:interval-1];
    }else {
        return nil;
    }
    NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
    [myDateFormatter setDateFormat:@"MM.dd"];
    NSString *beginString = [myDateFormatter stringFromDate:beginDate];
    NSString *endString = [myDateFormatter stringFromDate:endDate];
    
    return [NSString stringWithFormat:@"%@-%@",beginString,endString];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        [self performSegueWithIdentifier:@"CreateBill" sender:self];
    }
}

//TODO:缩放UIImage
- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
                                
    return scaledImage;
}
//自定长宽
- (UIImage *)reSizeImage:(UIImage *)image toSize:(CGSize)reSize

{
    UIGraphicsBeginImageContext(CGSizeMake(reSize.width, reSize.height));
    [image drawInRect:CGRectMake(0, 0, reSize.width, reSize.height)];
    UIImage *reSizeImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return reSizeImage;
    
}
@end
